#!/usr/bin/env python3
"""
简单爬虫演示路由
以 GitHub Trending 爬虫为例，提供任务式触发端点
"""

from flask import Blueprint, jsonify, request
import sys
import os
from datetime import datetime

# 添加路径 - 定位到项目根目录的 tools 文件夹
project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
scraper_path = os.path.join(project_root, 'tools', 'github_trending_scraper')
sys.path.insert(0, scraper_path)

from github_trending_scraper import GitHubTrendingScraper

bp = Blueprint('crawler', __name__)
scraper = GitHubTrendingScraper()


@bp.route('/run', methods=['POST'])
def run_task():
    """触发一次爬虫任务
    body 参数：
      - task: 任务类型（目前支持 github_trending）
      - language: 语言（可选）
      - since: 时间范围（daily/weekly/monthly，默认 daily）
      - limit: 数量（默认 20）
    """
    try:
        data = request.get_json(silent=True) or {}
        task = data.get('task', 'github_trending')
        if task != 'github_trending':
            return jsonify({'success': False, 'error': 'Unsupported task'}), 400

        language = data.get('language', '')
        since = data.get('since', 'daily')
        limit = int(data.get('limit', 20))

        repos = scraper.scrape_trending_repos(language=language, since=since, limit=limit)

        return jsonify({
            'success': True,
            'task': task,
            'params': {'language': language or 'all', 'since': since, 'limit': limit},
            'count': len(repos),
            'data': repos,
            'finished_at': datetime.utcnow().isoformat() + 'Z',
        }), 200
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


